<template>
  <div class="register">
    <h3 class="register-title">免费注册</h3>
    <van-form ref="registerForm" @submit="handleRegister" validate-first>
      <phone-field v-model="phone"/>
      <sms-captcha-field v-model="captchaCode" :loading="captchaLoading"
                         :sending="captchaSending" :time="captchaSendingTime"
                         @finish="captchaSending = false" @send="handleSendCaptcha"/>
      <van-field :type="passwordInvisible ? 'password' : 'text'"
                 name="password" placeholder="请输入密码" center
                 v-model="password" :right-icon="passwordInvisible ? 'eye-o' : 'closed-eye'"
                 @click-right-icon="passwordInvisible = !passwordInvisible"
                 :rules="[{ required: true, message: '密码不能为空' }]"/>
      <van-field :type="passwordInvisible ? 'password' : 'text'"
                 name="confirmPassword" placeholder="请再次输入密码" center
                 v-model="confirmPassword" :right-icon="passwordInvisible ? 'eye-o' : 'closed-eye'"
                 @click-right-icon="passwordInvisible = !passwordInvisible"
                 :rules="[{ required: true, message: '密码不能为空' },
                                { validator: confirmPasswordValidator, message: '两次输入密码不一致' }]"/>
      <van-button class="register-button" type="primary" block :loading="registering">
        立即注册
      </van-button>
    </van-form>
  </div>
</template>

<script>
import PhoneField from "@/views/user/PhoneField"
import { Button, Field, Form, Toast } from "vant"
import SmsCaptchaField from "@/views/user/SmsCaptchaField"
import { captcha, identity, message, security } from "@mall/api-services"
import md5 from "crypto-js/md5"

export default {
  name: "Register",
  components: {
    SmsCaptchaField,
    PhoneField,
    [Button.name]: Button,
    [Form.name]: Form,
    [Field.name]: Field,
  },
  data() {
    return {
      phone: "",
      captchaCode: "",
      passwordInvisible: true,
      password: "",
      confirmPassword: "",
      captchaLoading: false,
      captchaSendingTime: 60000,
      captchaSending: false,
      captchaToken: "",
      registering: false,
      fromLogin: false,
    }
  },
  beforeRouteEnter(to, from, next) {
    const { name } = from
    next(vm => vm.fromLogin = name === "Login")
  },
  methods: {
    confirmPasswordValidator(confirmPassword) {
      return this.password === confirmPassword
    },
    handleSendCaptcha() {
      this.$refs.registerForm.validate("phone")
          .then(() => {
            const { phone } = this
            const newCaptcha = new captcha.Captcha()
            newCaptcha.type = captcha.CaptchaType.Sms
            newCaptcha.parameters = {
              country_code: "86",
              phone,
            }
            this.captchaLoading = true
            captcha.CaptchaServiceV1.generateCaptcha(newCaptcha)
                .then(aCaptcha => {
                  this.captchaSendingTime = aCaptcha.intervals
                  this.captchaSending = true
                  this.captchaToken = aCaptcha.token
                })
                .then(() => Toast("验证码已发送"))
                .then(() => {
                  this.$refs.registerForm.validate("captchaCode")
                })
                .catch(({ response }) => Toast(message.getResponseMessage(response)))
                .finally(() => this.captchaLoading = false)
          })
    },
    handleRegister(values) {
      const password = md5(values.password).toString()
      const registration = new identity.UserRegistration()
      registration.countryCode = "86"
      registration.phone = values.phone
      registration.password = password
      registration.mode = identity.UserRegistration.Mode.PhoneCaptcha
      registration.captchaToken = this.captchaToken
      registration.captchaCode = values.captchaCode
      const { fromLogin } = this
      this.registering = true
      identity.UserServiceV1.createUser(registration)
          .then(aUser => {
            if (fromLogin) {
              this.$router.back()
            } else {
              this.$router.replace({
                path: "/login",
                query: {
                  phone: aUser.phone,
                  grant_type: security.CredentialsType.PhonePassword,
                },
              })
            }
          })
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
          .finally(() => this.registering = false)
    },
  },
}
</script>

<style lang="scss" scoped>
.register {
  padding: 20px 20px;

  .register-title {
    font-size: 24px;
    line-height: 1rem;
    font-weight: 500
  }

  .register-button {
    margin-top: 30px;
  }

  ::v-deep .van-field {
    background: inherit;
    padding: 10px 0;

    .van-field__label {
      width: 70px;
      flex: initial;
    }

    &:after {
      left: 0;
    }
  }
}
</style>
